import 'package:date_format/date_format.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:s_mankey/config/resource_mananger.dart';
import 'package:s_mankey/service/smonkey_repository.dart';
import 'package:s_mankey/ui/widget/custom_button.dart';
import 'package:s_mankey/ui/widget/error_widget.dart';
import 'package:s_mankey/ui/widget/loading_widget.dart';
import 'package:s_mankey/view_model/confirm_Invite_vmodel.dart';

class ConfirmInvite extends StatefulWidget {

  final arguments;

  ConfirmInvite({Key key,this.arguments}) : super(key: key);

  @override
  _ConfirmInviteState createState() {
    return _ConfirmInviteState();
  }
}

class _ConfirmInviteState extends State<ConfirmInvite> {

  Map options; //请求参数
  Map confirmOptions;
  var list  = [ { 'title' :'上课时间', 'result': ''},
    { 'title' :'上课城市', 'result': ''},
    { 'title' :'课程价格', 'result': ''},];

  // 数据源
  var datas;
  double fee; //应付金额

  //静态文字
  var desList = ['盛点可以兑换课程折扣，以支持自己或其他俱乐部粉丝持续学习。', '使用「盛点支持」时，每个课程只能使用一位学员的盛点，例如学员A支持自己报读溯源，他不能再使用学员B的盛点。', '邀请发出后，有效期为14天，若超过14天或以后，盛点没有被兑换，就会退回给发出邀请的学员', '受邀的学员会收到邀请码，在报名时，请向中心职员出示邀请码，受支持的学员若已完成报名手续，所使用之盛点不得退回。', ' 若有任何争议，盛幄集团保留最终之决定权。'];

  @override
  void initState() {
    print('收到的参数:${widget.arguments}');
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  // 初始化网络请求.
  Future loadData() async {
    List<Future> futures = [];
    futures.add(SmonkeysRepository.fetchMyInvitationCourseDetail(options: widget.arguments?? {}));
    futures.add(SmonkeysRepository.fetchMyInviteMiles(options: {'city': widget.arguments['city']}));
    return await Future.wait(futures);
  }

  @override
  Widget build(BuildContext context) {
    Provider.of<ConfirmInviteVModel>(context,listen: false).init();
    return Scaffold(
      appBar: AppBar(
        elevation: 0,
        title: Text('邀请详情'),
      ),
      body: FutureBuilder(future: loadData(),
          builder:
          (BuildContext context, AsyncSnapshot snapshot) {

        /// 请求中
        if (snapshot.connectionState != ConnectionState.done) {

          return LoadingWidget();
        }
        /// 请求结束
        if (snapshot.hasError) {
          // 请求失败，显示错误
          return datasErrorWidget(errorTip: snapshot.error.toString(),);
        }

        datas = snapshot.data[0];
        list[0]['result'] = datas['create_time'];
        list[1]['result'] = widget.arguments['city'];
        list[2]['result'] = datas['fee'];
        var milesData = snapshot.data[1];

        double miles = milesData['miles'].toDouble();
        fee = double.parse(datas['data_list'][0]['fee']);

        // 请求成功，显示数据
        return ListView(
        children: [
          Container(
              padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
              alignment: Alignment(-1,0),height: 44,child: Text(datas['member_name'],)),

          //封面内容
          Container(
            margin: EdgeInsets.fromLTRB(15, 0, 0, 0),
            padding: EdgeInsets.fromLTRB(0, 15, 0, 15),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Image.network(
                  datas['type_photo_link'],
                  width: 82,
                  height: 107,
                  fit: BoxFit.fill,
                ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.fromLTRB(10, 0, 10, 10),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        //标题
                        Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Text(datas['title']),
                            IconFonts.rightIcon,
                          ],
                        ),

                        //书内容
                        Container(
                          padding: EdgeInsets.fromLTRB(0, 5, 0, 5),
                          child: Text(
                            datas['type_short_desc'],
                            style: TextStyle(
                                color: Color(0xff747474),
                                fontSize: AppFontSize.Size14),
                            overflow: TextOverflow.ellipsis,
                            softWrap: true,
                            maxLines: 3,
                          ),
                        ),


                      ],
                    ),
                  ),
                ),
              ],
            ),
          ),

          Padding(
            padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
            child: ListView.builder(
              shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                itemCount: list.length,itemBuilder: (BuildContext context, int index){
              return Padding(
                padding: const EdgeInsets.only(top: 10),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                  Text(list[index]['title']),
                Text(list[index]['result']),
                ],),
              );
            }),
          ),


    Consumer(builder: (BuildContext context,
    ConfirmInviteVModel model, Widget child) {
    return Column(children: [
      //盛点折扣
      Padding(
        padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
        child: Column(children: [
          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Padding(
                  padding: const EdgeInsets.only(right: 10),
                  child: Text('盛点折扣'),
                ),
                Expanded(child:
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [

                        CountWidget(title: '-', onTap: (){
                          // 抵扣盛点不可低于10
                          if(model.curPay == 10) return;
                          model.onPayNum(num: -1);
                        }),

                        Padding(
                          padding: const EdgeInsets.fromLTRB(10,0,10,0),
                          child: Text(model.curPay.toString()),
                        ),

                        CountWidget(title: '+', onTap: (){
                          // 折扣不能超过可用盛点
                          if(model.curPay >= miles) return;
                          model.onPayNum(num: 1);
                        }),
                      ],),

                    Padding(
                      padding: const EdgeInsets.only(top: 2),
                      child: Text('可用盛点${miles.toString()} (最大赠送${datas['max_miles']})'),
                    ),
                  ],
                ),
                ),
                Text(model.curPay.toString()),
              ],),
          ),

          Padding(
            padding: const EdgeInsets.only(top: 10),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                Text('应付'),
                Text((fee - model.curPay).toString() ,style: TextStyle(color: Colors.red),),
              ],),
          )
        ],),
      ),

    ],);}),



          //课程描述
          Padding(
            padding: const EdgeInsets.fromLTRB(15, 0, 15, 10),
            child: Column(children: List.generate(desList.length,
                    (index) => Padding(padding:EdgeInsets.only(bottom: 10) ,
                      child: Row(
                      crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                      Text('${index}、'),
                      Expanded(child: Text(desList[index],softWrap: true,)),
                    ],),)),),
          ),

          Text('我已了解并同意使用条款', textAlign: TextAlign.center,),

           //同意按钮
          ///TODO: 同意条款邀请还没有完成
          GestureDetector(onTap: (){
//            city: "广佛"
//            city_english: "GZ"
//            course_code: "DS201008GZ"
//            course_name: "探索(DSV)"
//            course_time: "2020-10-08 00:00:00"
//            course_type: "D40"
//            member_id: "1572"
//            miles: 10
//            money: 11790
//            rate: "1"


          },child: CustomButton(
              padding: const EdgeInsets.fromLTRB(0, 10, 0, 10),
              margin: EdgeInsets.all(10),
              title: '同意条款，并邀请',
              fontSize: AppFontSize.Size20,
              fontColor: Colors.white,
              radius: 10.0,
              borderColor: Colors.transparent,
              gradient:AppColor.gradientColorHigh),),


        ],
      );}),
    );
  }

  Widget CountWidget({Function onTap, String title}){
    return GestureDetector(onTap: onTap,child: Container(
      child:
      Text(title,textAlign: TextAlign.center,),
      width: 30,
      height: 20,
      decoration: BoxDecoration(
          color:Colors.black54,borderRadius: BorderRadius.all(Radius.circular(10)) ),),);
  }
}
